package com.isyscore.os.metadata.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.isyscore.device.common.model.RespDTO;
import com.isyscore.os.core.exception.ErrorCode;
import com.isyscore.os.metadata.model.dto.req.MetricJobBatchQuery;
import com.isyscore.os.metadata.model.dto.req.MetricJobCronConfigReq;
import com.isyscore.os.metadata.model.entity.MetricJobBatch;
import com.isyscore.os.metadata.model.entity.MetricJobBatchResult;
import com.isyscore.os.metadata.service.impl.MetricCalculateService;
import com.isyscore.os.metadata.service.impl.MetricJobBatchService;
import com.isyscore.os.metadata.service.impl.MetricJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("${api-full-prefix}/metric/job")
@Api(tags = "数据指标任务调度")
@Slf4j
public class MetricJobController {

    @Autowired
    private MetricJobService metricJobService;

    @Autowired
    private MetricJobBatchService metricJobBatchService;

    @Autowired
    private MetricCalculateService metricCalculateService;

    @ApiOperation("分页查询数据指标定时调度的任务日志信息")
    @GetMapping("/log")
    public RespDTO<IPage<MetricJobBatch>> list(MetricJobBatchQuery pageQuery) {
        try {
            IPage<MetricJobBatch> logPage = metricJobBatchService.pageWithPageParam(pageQuery);
            return RespDTO.onSuc(logPage);
        } catch (Exception e) {
            //TODO 临时解决clickhouse在OS部署后第一次查询总是超时的问题
            try {
                IPage<MetricJobBatch> logPage = metricJobBatchService.pageWithPageParam(pageQuery);
                return RespDTO.onSuc(logPage);
            } catch (Exception e1) {
                log.error("查询数据指标定时调度的任务日志信息失败", e1);
                return RespDTO.onFail(ErrorCode.FAIL.getCode(), "数据库连接超时，请稍后再试");
            }
        }
    }

    @ApiOperation("(内部API)设置数据指标的计算任务调度信息")
    @PutMapping("/{metricId}")
    public RespDTO<?> configMetricJob(@PathVariable("metricId") Long metricId, @RequestBody @Validated MetricJobCronConfigReq metricJobDto) {
        metricJobService.refreshMetricJob(metricId, metricJobDto.getTaskCron());
        return RespDTO.onSuc();
    }

    @ApiOperation("(内部API)清除数据指标的计算任务的调度信息")
    @DeleteMapping("/{metricId}")
    public RespDTO<?> clearMetricJobInfo(@PathVariable("metricId") Long metricId) {
        metricJobService.deleteMetricJob(metricId);
        return RespDTO.onSuc();
    }

    @ApiOperation("(内部API)指标预计算接口")
    @PutMapping("/test/{metricId}")
    public RespDTO<List<MetricJobBatchResult>> testMetricJob(@PathVariable("metricId") Long metricId) {
        return RespDTO.onSuc(metricCalculateService.testMertricJob(metricId));
    }

}
